package com.maserb.monitor.web.author_manage;

import com.maserb.monitor.common.*;
import com.maserb.monitor.entity.JwOrgEntity;
import com.maserb.monitor.entity.Role;
import com.maserb.monitor.entity.SysCode;
import com.maserb.monitor.entity.UserEntity;
import com.maserb.monitor.entity.schoolOrg.SchoolUserOrgEntity;
import com.maserb.monitor.enums.SchoolNoticeTypeEnum;
import com.maserb.monitor.enums.SexTypeEnum;
import com.maserb.monitor.repository.schoolOrg.SchoolUserOrgRepository;
import com.maserb.monitor.service.author.impl.AuthorServiceImpl;
import com.maserb.monitor.service.author_manage.RoleService;
import com.maserb.monitor.service.author_manage.UserService;
import com.maserb.monitor.service.base.IToolService;
import com.maserb.monitor.service.jwEducation.JwOrgService;
import com.maserb.monitor.service.remote.EcCardService;
import com.maserb.monitor.service.sysCode.SysCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/author_manage/user")
public class UserController {
    @Autowired
    UserService userService;

    @Autowired
    AuthorServiceImpl authorService;

    @Autowired
    RoleService roleService;

    @Autowired
    private JwOrgService orgService;

    @Autowired
    private IToolService toolService;

    @Autowired
    private SchoolUserOrgRepository userOrgRepository;

    @Autowired
    private EcCardService ecCardService;

    @Autowired
    private SysCodeService codeService;

    @RequestMapping(value = {"/", "/index"})
    public ModelAndView getIndex(final HttpServletRequest request) {
        ModelAndView view = new ModelAndView();
        HttpSession session = request.getSession(true);
        UserEntity user = (UserEntity) session.getAttribute("user");
        String userId = "";
        if(null!=user && !"".equals(user.getId())){
            userId = user.getId();
        }
        view.setViewName("author_manage/user/index");

        view.addObject("userId",userId);
        return view;
    }

    @RequestMapping("/getEditUser/{id}")
    public ModelAndView getEditUser(@PathVariable final String id) {
        ModelAndView result = new ModelAndView();
        UserEntity entity = userService.findOne(id);
        List<JwOrgEntity>clazzList = new ArrayList<JwOrgEntity>();
        List<SchoolUserOrgEntity>userOrgEntityListOld = userOrgRepository.findByUser(entity);
        if(null!=userOrgEntityListOld && userOrgEntityListOld.size()>0){
            for(SchoolUserOrgEntity userOrgEntity:userOrgEntityListOld){
                JwOrgEntity orgEntity = userOrgEntity.getOrg();
                orgEntity.setParent(null);
                clazzList.add(orgEntity);
            }
        }
        entity.setClazzList(clazzList);
        result.setViewName("author_manage/user/edit");
        SexTypeEnum[] sexType = SexTypeEnum.values();
        List<SysCode>codeList = codeService.findByParent("SCHOOL_COURSE");
        result.addObject("codeList",codeList);
        result.addObject("sexType",sexType);
        result.addObject("entity", entity);
        List<Role> roles = roleService.findAll();
        result.addObject("roles", roles);
        return result;
    }

    @RequestMapping("/getEditPassword")
    public ModelAndView getEditPassword(HttpServletRequest request) {
        HttpSession session = request.getSession(true);
        UserEntity entity = (UserEntity) session.getAttribute("user");
        ModelAndView result = new ModelAndView();
        result.setViewName("author_manage/user/editPassword");
        result.addObject("entity", entity);
        return result;
    }

    @RequestMapping("/getView")
    public ModelAndView getView(HttpServletRequest request) {
        HttpSession session = request.getSession(true);
        UserEntity entity = (UserEntity) session.getAttribute("user");
        ModelAndView result = new ModelAndView();
        result.setViewName("author_manage/user/view");
        result.addObject("entity", entity);
        List<Role> roles = roleService.findAll();
        result.addObject("roles", roles);
        return result;
    }

    @RequestMapping("/doUpdateUser")
    @ResponseBody
    public AjaxResult<Boolean> doUpdateUser(UserEntity entity) {
        return AjaxUtils.process(new Func_T<Boolean>() {
            @Override
            public Boolean invoke() throws Exception {
                UserEntity userEntity = userService.findOne(entity.getId());
                /*userEntity.setUserName(entity.getUserName());*/
                userEntity.setRole(entity.getRole());
                List<JwOrgEntity>clazzList = new ArrayList<JwOrgEntity>();
                List<SchoolUserOrgEntity>userOrgEntityListOld = userOrgRepository.findByUser(entity);
                userOrgRepository.deleteAll(userOrgEntityListOld);
                if(null!=entity.getClazzList() && entity.getClazzList().size()>0){
                    clazzList = entity.getClazzList();
                    List<SchoolUserOrgEntity>userOrgEntityList = new ArrayList<SchoolUserOrgEntity>();
                    for(JwOrgEntity orgEntity:clazzList){
                        SchoolUserOrgEntity userOrgEntity = new SchoolUserOrgEntity();
                        userOrgEntity.setUser(entity);
                        userOrgEntity.setOrg(orgEntity);
                        userOrgEntityList.add(userOrgEntity);
                    }
                    userOrgRepository.saveAll(userOrgEntityList);
                }
                userEntity.setIdcard(entity.getIdcard());
                userEntity.setRealName(entity.getRealName());
                userEntity.setAddress(entity.getAddress());
                userEntity.setOrgId(entity.getOrgId());
                userEntity.setImage(entity.getImage());
                userEntity.setSex(entity.getSex());
                userEntity.setPhoneNumber(entity.getPhoneNumber());
                userEntity.setSysCodeId(entity.getSysCodeId());
                userEntity.setCardNumber(entity.getCardNumber());
                userEntity.setTeacherId(entity.getTeacherId());
                if(null!=entity.getOrgId() && !"".equals(entity.getOrgId())){
                    JwOrgEntity orgEntity = orgService.findOne(entity.getOrgId());
                    userEntity.setOrgName(orgEntity.getName());
                    userEntity.setDid(orgEntity.getDid());
                }
                userEntity.setDescription(entity.getDescription());
                userService.save(userEntity);
                ecCardService.doUpdateTeacher(userEntity);
                return true;
            }
        });
    }

    @RequestMapping("/doUpdatePassword")
    @ResponseBody
    public AjaxResult<Boolean> doUpdatePassword(UserEntity entity,String oldPassword) {
        return AjaxUtils.process(new Func_T<Boolean>() {
            @Override
            public Boolean invoke() throws Exception {
                UserEntity userEntity = userService.findOne(entity.getId());
                if(!oldPassword.equals(userEntity.getPassword())){
                    throw new Exception("原密码错误");
                }else{
                    userEntity.setPassword(entity.getPassword());
                    userService.save(userEntity);
                }
                return true;
            }
        });
    }

    @RequestMapping("/getAddUser")
    public ModelAndView getAddUser() {
        ModelAndView result = new ModelAndView();
        result.setViewName("author_manage/user/add");
        SexTypeEnum[] sexType = SexTypeEnum.values();
        result.addObject("sexType",sexType);
        List<Role> roles = roleService.findAll();
        List<JwOrgEntity> orgList = orgService.findAll();
        List<SysCode>codeList = codeService.findByParent("SCHOOL_COURSE");
        result.addObject("orgList",orgList);
        result.addObject("codeList",codeList);
        result.addObject("roles", roles);
        return result;
    }

    @RequestMapping("/doListUser")
    @ResponseBody
    public PageResponseResult<UserEntity> doListUser(PageRequestParam page,String userId, final String userName,final String realName,final String orgId) {
        Sort.Order codeOrder = new Sort.Order(Sort.Direction.DESC, "createTime");
        List<Sort.Order> orderList = new ArrayList<Sort.Order>();
        orderList.add(codeOrder);
        Sort sort = new Sort(orderList);
        return AjaxUtils.processPage(page,sort, new Func_T1<PageRequest, Page<UserEntity>>() {
            @Override
            public Page<UserEntity> invoke(PageRequest var1) throws Exception {
                String clazzId ="";
                if(!StringUtils.isEmptyOrWhitespace(userId)){
                    UserEntity user = userService.findOne(userId);
                    if(null!=user&&!"".equals(user.getId())){
                        clazzId = user.getOrgId();
                        JwOrgEntity orgEntity = orgService.findOne(clazzId);
                        if(null!=orgEntity && orgEntity.getTreeLevel()==0){
                            clazzId ="";
                        }
                    }
                }
                Page<UserEntity> page = userService.findAll(var1,clazzId, userName,realName,orgId);
                for(UserEntity entity:page.getContent()){
                    if(null!=entity.getRole() && !"".equals(entity.getRole())){
                        entity.setRole(toolService.getRoleName(entity.getRole()));
                    }
                    /*if(null!=entity.getOrgId() && !"".equals(entity.getOrgId())){
                        entity.setOrgName(toolService.getOrgName(entity.getOrgId()));
                    }*/
                }
                return page;
            }
        });
    }


    @RequestMapping("/doAddUser")
    @ResponseBody
    public AjaxResult<Boolean> doAddUser(UserEntity entity) {
        return AjaxUtils.process(new Func_T<Boolean>() {
            @Override
            public Boolean invoke() throws Exception {
                UserEntity userEntity = userService.findByUserName(entity.getUserName());
                if(null!=userEntity && null!=userEntity.getId() &&!"".equals(userEntity.getId())){
                    throw new Exception("已注册该用户");
                }
                List<JwOrgEntity>clazzList = new ArrayList<JwOrgEntity>();

                entity.setCreateTime(CreateTimeUtils.getCreateTime());
                entity.setPassword("123456");
                entity.setSalt(IdUtils.generateId());
                if(null!=entity.getOrgId() && !"".equals(entity.getOrgId())){
                    JwOrgEntity orgEntity = orgService.findOne(entity.getOrgId());
                    entity.setOrgName(orgEntity.getName());
                    entity.setDid(orgEntity.getDid());
                }
                /*Long cid = ecCardService.doAddTeacher(entity);
                if(null!=cid){
                    entity.setCid(cid);
                }*/
                userService.save(entity);
                if(null!=entity.getClazzList() && entity.getClazzList().size()>0){
                    clazzList = entity.getClazzList();
                    List<SchoolUserOrgEntity>userOrgEntityList = new ArrayList<SchoolUserOrgEntity>();
                    for(JwOrgEntity orgEntity:clazzList){
                        SchoolUserOrgEntity userOrgEntity = new SchoolUserOrgEntity();
                        userOrgEntity.setUser(entity);
                        userOrgEntity.setOrg(orgEntity);
                        userOrgEntityList.add(userOrgEntity);
                    }
                    userOrgRepository.saveAll(userOrgEntityList);
                }
                //传入用户名、密码、昵称
                JpushImClientUtil.addUser(entity.getUserName(),entity.getPassword(),entity.getRealName());
                return true;
            }
        });
    }


    @RequestMapping(value = "/exportUserLists")
    public void exportUserLists(HttpServletResponse response,final String userId, final String userName,final String realName,final String orgId) {
        //模拟从数据库获取需要导出的数据
        String clazzId ="";
        if(!StringUtils.isEmptyOrWhitespace(userId)){
            UserEntity user = userService.findOne(userId);
            if(null!=user&&!"".equals(user.getId())){
                clazzId = user.getOrgId();
                JwOrgEntity orgEntity = orgService.findOne(clazzId);
                if(null!=orgEntity && orgEntity.getTreeLevel()==0){
                    clazzId ="";
                }
            }
        }
        List<UserEntity> userLists = userService.findAll(clazzId,userName,realName,orgId);
        /*for (UserEntity entity : userLists) {
            entity.setBkfwCn(toolService.getDataTypeName("area_code", black.getBkfw()));
            entity.setFmtCreateDate(toolService.formatYYMMDDHHMMSS(black.getCreateDate()));
        }*/
        String name = "用户列表";
        String fileName="";
        try{
            //fileName  = new String(name.getBytes("GBK"),"ISO-8859-1")+ System.currentTimeMillis()+".xls";
            fileName  = name + System.currentTimeMillis()+".xls";
        }catch (Exception e){
            e.printStackTrace();
        }
        //导出操作
        ExcelExportUtils.exportExcel(userLists, name, "", UserEntity.class, fileName, response);
    }



    //重置用户密码(123456)
    @RequestMapping("/doReset")
    @ResponseBody
    public AjaxResult<Boolean> doReset(@RequestParam(value = "keys[]") ArrayList<String> keys)
    {
        return AjaxUtils.process(new Func_T<Boolean>() {
            @Override
            public Boolean invoke() throws Exception {
                keys.forEach(id -> userService.doReset(id));
                return true;
            }
        });
    }

    @RequestMapping("/doDeleteUser")
    @ResponseBody
    public AjaxResult<Boolean> doDeleteUser(@RequestParam(value = "keys[]") ArrayList<String> keys) {
        return AjaxUtils.process(new Func_T<Boolean>() {
            @Override
            public Boolean invoke() throws Exception {
                userService.deleteAllByKeys(keys);
                return true;
            }
        });
    }
}
